import React, { useState, useEffect } from 'react';
import { Box, Typography, Card, CardContent, Grid, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button, TextField, Dialog, DialogTitle, DialogContent, DialogActions, Chip, FormControl, InputLabel, Select, MenuItem, Switch, FormControlLabel, Divider } from '@mui/material';
import { Lock, Shield, Info, ChevronRight, AddCircle, Edit, Delete, Search, Refresh, FilterList, Save, Cancel } from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';

const DataClassification = () => {
  const [dataCategories, setDataCategories] = useState([]);
  const [permissions, setPermissions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [userData, setUserData] = useState(null);
  const [userVehicleId, setUserVehicleId] = useState('vehicle-1'); // 用户绑定的车辆ID
  const [openCategoryDialog, setOpenCategoryDialog] = useState(false);
  const [openPermissionDialog, setOpenPermissionDialog] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState(null);
  const [selectedPermission, setSelectedPermission] = useState(null);
  const [categoryForm, setCategoryForm] = useState({ name: '', description: '', parentId: '' });
  const [permissionForm, setPermissionForm] = useState({ name: '', attributes: [], accessPolicy: 1 });
  const [searchTerm, setSearchTerm] = useState('');
  const navigate = useNavigate();

  // 第一个useEffect: 获取用户信息和用户绑定的车辆ID
  useEffect(() => {
    // 获取用户信息
    const savedUserInfo = localStorage.getItem('userInfo');
    let userInfo = null;
    if (savedUserInfo) {
      try {
        userInfo = JSON.parse(savedUserInfo);
        setUserData(userInfo);
      } catch (error) {
        console.error('Failed to parse user info:', error);
      }
    }

    // 获取用户绑定的车辆ID
    try {
      const userVehicleBindings = JSON.parse(localStorage.getItem('userVehicleBindings') || '{}');
      let vehicleId = userVehicleBindings[userInfo?.id];
      
      // 如果没有绑定关系，使用默认车辆ID
      if (!vehicleId) {
        const mockVehicles = JSON.parse(localStorage.getItem('mockVehicles') || '[]');
        vehicleId = mockVehicles.length > 0 ? mockVehicles[0].id : 'vehicle-1';
      }
      setUserVehicleId(vehicleId);
    } catch (error) {
      console.error('Failed to get user vehicle binding:', error);
      setUserVehicleId('vehicle-1'); // 默认值
    }
  }, []);

  // 第二个useEffect: 加载数据分类和权限设置，依赖于userVehicleId
  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        
        // 在开发环境中使用模拟数据
        if (process.env.NODE_ENV === 'development') {
          // 从localStorage获取或创建模拟数据
          const storedCategories = localStorage.getItem('dataCategories');
          const storedPermissions = localStorage.getItem('dataPermissions');
          
          if (storedCategories) {
            setDataCategories(JSON.parse(storedCategories));
          } else {
            const mockCategories = [
              {
                id: 'cat1',
                name: '维修数据',
                description: '车辆维修记录、保养信息等',
                parentId: null,
                permissionId: 'perm1'
              },
              {
                id: 'cat2',
                name: '运行数据',
                description: '车辆行驶数据、发动机状态等',
                parentId: null,
                permissionId: 'perm2'
              },
              {
                id: 'cat3',
                name: '行车记录数据',
                description: '行车记录仪数据、GPS轨迹等',
                parentId: null,
                permissionId: 'perm3'
              },
              {
                id: 'cat4',
                name: '部件维修',
                description: '各部件的维修记录',
                parentId: 'cat1',
                permissionId: 'perm1'
              },
              {
                id: 'cat5',
                name: '保养计划',
                description: '定期保养计划及执行记录',
                parentId: 'cat1',
                permissionId: 'perm1'
              }
            ];
            setDataCategories(mockCategories);
            localStorage.setItem('dataCategories', JSON.stringify(mockCategories));
          }
          
          if (storedPermissions) {
            setPermissions(JSON.parse(storedPermissions));
          } else {
            const mockPermissions = [
              {
                id: 'perm1',
                name: '维修数据访问',
                attributes: [
                  { name: 'maintenance', value: 1 },
                  { name: 'repair', value: 1 },
                  { name: 'vehicleId', value: userVehicleId }
                ],
                accessPolicy: 1 // 1=需要有该属性, -1=需要没有该属性
              },
              {
                id: 'perm2',
                name: '运行数据访问',
                attributes: [
                  { name: 'operation', value: 1 },
                  { name: 'real-time', value: 1 },
                  { name: 'vehicleId', value: userVehicleId }
                ],
                accessPolicy: 1
              },
              {
                id: 'perm3',
                name: '行车记录访问',
                attributes: [
                  { name: 'tracking', value: 1 },
                  { name: 'privacy', value: 0 },
                  { name: 'vehicleId', value: userVehicleId }
                ],
                accessPolicy: 1
              }
            ];
            setPermissions(mockPermissions);
            localStorage.setItem('dataPermissions', JSON.stringify(mockPermissions));
          }
        }
        
        setError(null);
      } catch (err) {
        console.error('Failed to load data classification:', err);
        setError('Failed to load data classification. Please try again later.');
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, [userVehicleId]);

  // 打开添加/编辑数据分类对话框
  const handleOpenCategoryDialog = (category = null) => {
    if (category) {
      setSelectedCategory(category);
      setCategoryForm({ 
        name: category.name, 
        description: category.description, 
        parentId: category.parentId || '' 
      });
    } else {
      setSelectedCategory(null);
      setCategoryForm({ name: '', description: '', parentId: '' });
    }
    setOpenCategoryDialog(true);
  };

  // 关闭数据分类对话框
  const handleCloseCategoryDialog = () => {
    setOpenCategoryDialog(false);
    setSelectedCategory(null);
    setCategoryForm({ name: '', description: '', parentId: '' });
  };

  // 提交数据分类表单
  const handleSubmitCategoryForm = () => {
    const updatedCategories = [...dataCategories];
    
    if (selectedCategory) {
      // 更新现有分类
      const index = updatedCategories.findIndex(c => c.id === selectedCategory.id);
      if (index !== -1) {
        updatedCategories[index] = {
          ...updatedCategories[index],
          name: categoryForm.name,
          description: categoryForm.description,
          parentId: categoryForm.parentId || null
        };
      }
    } else {
      // 添加新分类
      const newCategory = {
        id: `cat${Date.now()}`,
        name: categoryForm.name,
        description: categoryForm.description,
        parentId: categoryForm.parentId || null,
        permissionId: permissions[0]?.id || ''
      };
      updatedCategories.push(newCategory);
    }
    
    setDataCategories(updatedCategories);
    localStorage.setItem('dataCategories', JSON.stringify(updatedCategories));
    handleCloseCategoryDialog();
  };

  // 打开添加/编辑权限对话框
  const handleOpenPermissionDialog = (permission = null) => {
    if (permission) {
      setSelectedPermission(permission);
      setPermissionForm({ 
        name: permission.name, 
        attributes: [...permission.attributes], 
        accessPolicy: permission.accessPolicy 
      });
    } else {
      setSelectedPermission(null);
      setPermissionForm({ name: '', attributes: [{ name: '', value: 1 }], accessPolicy: 1 });
    }
    setOpenPermissionDialog(true);
  };

  // 关闭权限对话框
  const handleClosePermissionDialog = () => {
    setOpenPermissionDialog(false);
    setSelectedPermission(null);
    setPermissionForm({ name: '', attributes: [{ name: '', value: 1 }], accessPolicy: 1 });
  };

  // 提交权限表单
  const handleSubmitPermissionForm = () => {
    const updatedPermissions = [...permissions];
    
    if (selectedPermission) {
      // 更新现有权限
      const index = updatedPermissions.findIndex(p => p.id === selectedPermission.id);
      if (index !== -1) {
        updatedPermissions[index] = {
          ...updatedPermissions[index],
          name: permissionForm.name,
          attributes: permissionForm.attributes,
          accessPolicy: permissionForm.accessPolicy
        };
      }
    } else {
      // 添加新权限
      const newPermission = {
        id: `perm${Date.now()}`,
        name: permissionForm.name,
        attributes: permissionForm.attributes,
        accessPolicy: permissionForm.accessPolicy
      };
      updatedPermissions.push(newPermission);
    }
    
    setPermissions(updatedPermissions);
    localStorage.setItem('dataPermissions', JSON.stringify(updatedPermissions));
    handleClosePermissionDialog();
  };

  // 添加新的属性
  const addAttribute = () => {
    setPermissionForm(prev => ({
      ...prev,
      attributes: [...prev.attributes, { name: '', value: 1 }]
    }));
  };

  // 删除属性
  const removeAttribute = (index) => {
    if (permissionForm.attributes.length <= 1) return;
    
    const updatedAttributes = [...permissionForm.attributes];
    updatedAttributes.splice(index, 1);
    
    setPermissionForm(prev => ({
      ...prev,
      attributes: updatedAttributes
    }));
  };

  // 更新属性值
  const updateAttribute = (index, field, value) => {
    const updatedAttributes = [...permissionForm.attributes];
    updatedAttributes[index] = {
      ...updatedAttributes[index],
      [field]: value
    };
    
    setPermissionForm(prev => ({
      ...prev,
      attributes: updatedAttributes
    }));
  };

  // 获取权限名称
  const getPermissionName = (permissionId) => {
    const permission = permissions.find(p => p.id === permissionId);
    return permission ? permission.name : '未设置';
  };

  // 格式化访问策略
  const formatAccessPolicy = (policy) => {
    return policy === 1 ? '需要有该属性' : '需要没有该属性';
  };

  // 过滤数据分类
  const filteredCategories = dataCategories.filter(category => 
    category.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    category.description.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <Box sx={{ p: 3 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          <span style={{ display: 'flex', alignItems: 'center' }}>
            <Lock sx={{ mr: 2 }} />
            数据分类及权限
          </span>
        </Typography>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button 
            variant="contained" 
            color="primary" 
            startIcon={<AddCircle />}
            onClick={() => handleOpenCategoryDialog()}
          >
            添加数据分类
          </Button>
          <Button 
            variant="outlined" 
            color="primary" 
            startIcon={<AddCircle />}
            onClick={() => handleOpenPermissionDialog()}
          >
            添加权限策略
          </Button>
        </div>
      </div>
      
      {loading && (
        <Typography variant="body1">加载数据中...</Typography>
      )}
      
      {error && (
        <div style={{ color: 'error.main', marginBottom: 2 }}>{error}</div>
      )}
      
      {!loading && (
        <>
          {/* 权限策略卡片 */}
          <Card sx={{ mb: 4 }}>
            <CardContent>
              <Typography variant="h6" gutterBottom>
                权限策略列表
              </Typography>
              <Grid container spacing={3}>
                {permissions.map(permission => (
                  <Grid item xs={12} sm={6} md={4} key={permission.id}>
                    <Card variant="outlined" sx={{ height: '100%' }}>
                      <CardContent>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                          <Typography variant="subtitle1">{permission.name}</Typography>
                          <Button 
                            variant="text" 
                            color="primary" 
                            size="small" 
                            onClick={() => handleOpenPermissionDialog(permission)}
                          >
                            编辑
                          </Button>
                        </div>
                        <Typography variant="body2" color="text.secondary" gutterBottom>
                          访问策略: {formatAccessPolicy(permission.accessPolicy)}
                        </Typography>
                        <Divider sx={{ mb: 2 }} />
                        <Typography variant="subtitle2" gutterBottom>
                          属性要求:
                        </Typography>
                        {permission.attributes.map((attr, index) => (
                          <Chip 
                            key={index} 
                            label={`${attr.name}: ${attr.value}`} 
                            size="small" 
                            sx={{ m: 0.5 }}
                          />
                        ))}
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            </CardContent>
          </Card>
          
          {/* 数据分类表格 */}
          <Card>
            <CardContent>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 2 }}>
                <Typography variant="h6" component="div">
                  数据分类列表
                </Typography>
                <div style={{ display: 'flex', gap: 1 }}>
                  <TextField
                    label="搜索分类"
                    variant="outlined"
                    size="small"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    InputProps={{ startAdornment: <Search size="small" />, style: { width: 200 } }}
                  />
                  <Button size="small" variant="outlined" startIcon={<Refresh />}>
                    刷新
                  </Button>
                </div>
              </div>
              
              {filteredCategories.length === 0 ? (
                <Typography variant="body1">暂无数据分类</Typography>
              ) : (
                <TableContainer component={Paper}>
                  <Table sx={{ minWidth: 650 }} aria-label="data classification table">
                    <TableHead>
                      <TableRow>
                        <TableCell>分类名称</TableCell>
                        <TableCell>描述</TableCell>
                        <TableCell>父分类</TableCell>
                        <TableCell>权限策略</TableCell>
                        <TableCell align="right">操作</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {filteredCategories.map((category) => {
                        const parentCategory = dataCategories.find(c => c.id === category.parentId);
                        return (
                          <TableRow
                            key={category.id}
                            sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                          >
                            <TableCell component="th" scope="row">
                              {category.name}
                            </TableCell>
                            <TableCell>{category.description}</TableCell>
                            <TableCell>{parentCategory ? parentCategory.name : '-'}</TableCell>
                            <TableCell>{getPermissionName(category.permissionId)}</TableCell>
                            <TableCell align="right">
                              <Button 
                                variant="text" 
                                color="primary"
                                size="small"
                                onClick={() => handleOpenCategoryDialog(category)}
                              >
                                编辑
                              </Button>
                            </TableCell>
                          </TableRow>
                        );
                      })}
                    </TableBody>
                  </Table>
                </TableContainer>
              )}
            </CardContent>
          </Card>
        </>
      )}
      
      {/* 数据分类对话框 */}
      <Dialog 
        open={openCategoryDialog} 
        onClose={handleCloseCategoryDialog}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>{selectedCategory ? '编辑数据分类' : '添加数据分类'}</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="分类名称"
            fullWidth
            value={categoryForm.name}
            onChange={(e) => setCategoryForm(prev => ({ ...prev, name: e.target.value }))}
          />
          <TextField
            margin="dense"
            label="描述"
            fullWidth
            multiline
            rows={3}
            value={categoryForm.description}
            onChange={(e) => setCategoryForm(prev => ({ ...prev, description: e.target.value }))}
          />
          <FormControl fullWidth margin="dense">
            <InputLabel>父分类</InputLabel>
            <Select
              value={categoryForm.parentId}
              onChange={(e) => setCategoryForm(prev => ({ ...prev, parentId: e.target.value }))}
              label="父分类"
            >
              <MenuItem value="">无父分类</MenuItem>
              {dataCategories
                .filter(c => !selectedCategory || c.id !== selectedCategory.id)
                .map(category => (
                  <MenuItem key={category.id} value={category.id}>{category.name}</MenuItem>
                ))
              }
            </Select>
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseCategoryDialog} startIcon={<Cancel />}>取消</Button>
          <Button onClick={handleSubmitCategoryForm} startIcon={<Save />} color="primary">保存</Button>
        </DialogActions>
      </Dialog>
      
      {/* 权限策略对话框 */}
      <Dialog 
        open={openPermissionDialog} 
        onClose={handleClosePermissionDialog}
        fullWidth
        maxWidth="md"
      >
        <DialogTitle>{selectedPermission ? '编辑权限策略' : '添加权限策略'}</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="权限名称"
            fullWidth
            value={permissionForm.name}
            onChange={(e) => setPermissionForm(prev => ({ ...prev, name: e.target.value }))}
          />
          <FormControl fullWidth margin="dense">
            <InputLabel>访问策略</InputLabel>
            <Select
              value={permissionForm.accessPolicy}
              onChange={(e) => setPermissionForm(prev => ({ ...prev, accessPolicy: e.target.value }))}
              label="访问策略"
            >
              <MenuItem value={1}>需要有该属性</MenuItem>
              <MenuItem value={-1}>需要没有该属性</MenuItem>
            </Select>
          </FormControl>
          <Typography variant="subtitle2" gutterBottom sx={{ mt: 2 }}>
            属性列表:
          </Typography>
          {permissionForm.attributes.map((attr, index) => (
            <Grid container spacing={2} key={index} sx={{ mb: 1 }}>
              <Grid item xs={5}>
                <TextField
                  label="属性名称"
                  fullWidth
                  size="small"
                  value={attr.name}
                  onChange={(e) => updateAttribute(index, 'name', e.target.value)}
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  label="属性值"
                  fullWidth
                  size="small"
                  type="number"
                  value={attr.value}
                  onChange={(e) => updateAttribute(index, 'value', parseInt(e.target.value))}
                />
              </Grid>
              <Grid item xs={3}>
                <Button 
                  variant="outlined" 
                  color="error" 
                  size="small"
                  fullWidth
                  onClick={() => removeAttribute(index)}
                  disabled={permissionForm.attributes.length <= 1}
                >
                  删除
                </Button>
              </Grid>
            </Grid>
          ))}
          <Button 
            variant="text" 
            color="primary" 
            startIcon={<AddCircle />}
            onClick={addAttribute}
          >
            添加属性
          </Button>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClosePermissionDialog} startIcon={<Cancel />}>取消</Button>
          <Button onClick={handleSubmitPermissionForm} startIcon={<Save />} color="primary">保存</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default DataClassification;